package com.lianjia.sh.se.esb.client.service.impl;

import com.dooioo.dymq.sender.common.AbstractSender;
import com.dooioo.plus.DyPlusConfig;
import com.lianjia.sh.se.esb.client.service.MQMessageService;
import com.lianjia.sh.se.esb.client.service.support.SimpleActiveMqSender;
import com.lianjia.sh.se.esb.spi.util.MessageUtil;
import org.apache.activemq.spring.ActiveMQConnectionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * Created by yangsp1 on 16/7/15.
 */
@Service
public class ActiveMqMessageService extends AbstractSender  implements MQMessageService,ApplicationContextAware {
    Logger logger = LoggerFactory.getLogger(ActiveMqMessageService.class);
    ApplicationContext applicationContext;
    Map<String,AbstractSender> senderCache = new HashMap<>();

    @Override
    protected void log(String s, String s1) {

    }

    public void sendMessage(String projectType, String serviceType, String message) throws Exception {
        AbstractSender abstractSender = getSender(projectType,serviceType);
        abstractSender.sendMessage(message);
    }

    /**
     * 动态生成sender：根据projectType,serviceType,env
     * @param projectType
     * @param serviceType
     * @return
     */
    public AbstractSender getSender(String projectType, String serviceType){
        String env = DyPlusConfig.getInstance().getEnv();
        String destinationName = MessageUtil.getMQName(projectType,serviceType,env);
        AbstractSender abstractSender = senderCache.get(destinationName);
        if(abstractSender != null){
            return abstractSender;
        }

        abstractSender = new SimpleActiveMqSender();
        ActiveMQConnectionFactory inConnectionFactory = (ActiveMQConnectionFactory)applicationContext.getBean("activemq.in.connectionFactory", ActiveMQConnectionFactory.class);
        abstractSender.setConnectionFactory(inConnectionFactory);
        abstractSender.setDestinationName(destinationName);
        senderCache.put(destinationName,abstractSender);
        return abstractSender;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
